// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.ReportReceivable;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.ReportReceivableDetailMapper;
import com.fowo.api.mapper.ReportReceivableMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.SysCountryMapper;
import com.fowo.api.model.report.receivable.ReportReceivableExcelPo;
import com.fowo.api.model.report.receivable.ReportReceivableImportPo;
import com.fowo.api.model.report.receivable.ReportReceivableItemVo;
import com.fowo.api.model.report.receivable.ReportReceivableManageAction;
import com.fowo.api.model.report.receivable.ReportReceivableReconciliationAction;
import com.fowo.api.model.report.receivable.ReportReceivableSearchParamPo;
import com.fowo.api.model.report.receivable.ReportReceivableUploadRecordAction;
import com.fowo.api.model.report.receivable.ReportReceivableVo;
import com.fowo.api.model.report.receivable.constant.ReportReceivableArchiveStatusEnums;
import com.fowo.api.model.report.receivable.constant.ReportReceivableReceivedStateEnums;
import com.fowo.api.model.report.receivable.detail.ReportReceivableDetailSearchParamPo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.sys.country.SysCountryItemVo;
import com.fowo.api.model.sys.country.SysCountrySearchParamPo;
import com.fowo.api.service.ReportReceivableDetailService;
import com.fowo.api.service.ReportReceivableService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 应收报告 服务实现基类
 * @author 蜂窝蜜造平台 配置人：吕家傲
 */
@Slf4j
@DataObjectType(ReportReceivable.class)
@DS("ds24")
public class ReportReceivableBaseServiceImpl
  extends ServiceImpl<ReportReceivableMapper, ReportReceivable>
  implements ReportReceivableService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("sidsShopName", "si.`shop_name`");
      put("midsCountry", "sc.`country`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected ReportReceivableService self;

  @Resource
  protected ReportReceivableDetailService reportReceivableDetailService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected SysCountryMapper sysCountryMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected ReportReceivableReconciliationAction reportReceivableReconciliationAction;

  @Autowired(required = false)
  protected ReportReceivableManageAction reportReceivableManageAction;

  @Autowired(required = false)
  protected ReportReceivableUploadRecordAction reportReceivableUploadRecordAction;

  @Resource
  protected Validator validator;

  /**
   * 创建应收报告
   * @param model 应收报告
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(ReportReceivableVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    ReportReceivable entity = new ReportReceivable();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("应收报告保存失败");
  }

  /**
   * 更新所有子表
   * @param model 应收报告
   */
  protected void updateAllChilds(ReportReceivableVo model) throws Exception {
    if (model.getDetail() != null) {
      reportReceivableDetailService.saveAllByParentReportReceivable(
        model.getId(),
        model.getDetail()
      );
    }
  }

  /**
   * 更新应收报告
   * @param model 应收报告
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(ReportReceivableVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    ReportReceivable entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("应收报告不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新应收报告（带空值）
   * @param model 应收报告
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(ReportReceivableVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    ReportReceivable entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("应收报告不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(ReportReceivable::getSids, model.getSids())
      .set(ReportReceivable::getStoreName, model.getStoreName())
      .set(ReportReceivable::getMids, model.getMids())
      .set(ReportReceivable::getLastUpdateTime, model.getLastUpdateTime())
      .set(ReportReceivable::getLastUpdateUser, model.getLastUpdateUser())
      .set(ReportReceivable::getSettleMonth, model.getSettleMonth())
      .set(ReportReceivable::getArchiveStatus, model.getArchiveStatus())
      .set(ReportReceivable::getCurrencyCode, model.getCurrencyCode())
      .set(
        ReportReceivable::getBeginningBalanceCurrencyAmount,
        model.getBeginningBalanceCurrencyAmount()
      )
      .set(ReportReceivable::getIncomeAmount, model.getIncomeAmount())
      .set(ReportReceivable::getRefundAmount, model.getRefundAmount())
      .set(ReportReceivable::getSpendAmount, model.getSpendAmount())
      .set(ReportReceivable::getOther, model.getOther())
      .set(
        ReportReceivable::getConvertedSuccessAmount,
        model.getConvertedSuccessAmount()
      )
      .set(
        ReportReceivable::getConvertedFailedAmount,
        model.getConvertedFailedAmount()
      )
      .set(ReportReceivable::getEndingBalance, model.getEndingBalance())
      .set(ReportReceivable::getRemark, model.getRemark())
      .set(ReportReceivable::getReceivedState, model.getReceivedState())
      .set(ReportReceivable::getCurrencyIcon, model.getCurrencyIcon())
      .eq(ReportReceivable::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(ReportReceivableSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 应收详情(detail) 对应的对象
    ReportReceivableDetailSearchParamPo detailSearchParam =
      new ReportReceivableDetailSearchParamPo();
    detailSearchParam.setDisableDataPremissions(true);
    detailSearchParam.setParentReportReceivableInList(ids);
    ReportReceivableDetailMapper localReportReceivableDetailMapper =
      ContextHolder
        .getApplicationContext()
        .getBean(ReportReceivableDetailMapper.class);
    detailSearchParam.applySqlSegments();
    List<Long> detailIdList = localReportReceivableDetailMapper.searchIds(
      detailSearchParam
    );
    if (!detailIdList.isEmpty()) {
      ReportReceivableDetailService localReportReceivableDetailService =
        ContextHolder
          .getApplicationContext()
          .getBean(ReportReceivableDetailService.class);
      localReportReceivableDetailService.batchDelete(detailIdList);
    }
  }

  /**
   * 删除应收报告
   * @param id 应收报告的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除应收报告
   * @param ids 应收报告的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<ReportReceivableImportPo> excelToImportRow(
    ReportReceivableImportPo row,
    Integer rowNumber,
    ReportReceivableVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<ReportReceivableImportPo> ir =
      new ImportRow<ReportReceivableImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<ReportReceivableImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new ReportReceivableVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, ReportReceivableImportPo.class);

    // 一般数据处理
    vo.setSettleMonth(SheetUtils.tryToDate(row.getSettleMonth()));
    SheetUtils.datePreviewFormat(row.getSettleMonth(), row::setSettleMonth);
    if (StringUtils.hasText(row.getArchiveStatus())) {
      vo.setArchiveStatus(
        ReportReceivableArchiveStatusEnums.toValue(row.getArchiveStatus())
      );
      if (vo.getArchiveStatus() == null) {
        ir.addError("archiveStatus", "对账状态只能是：“已对账”, “未对账”");
      }
    }
    if (StringUtils.hasText(row.getCurrencyCode())) {
      List<SysDictAllItem> currencyCodeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "currencyCode",
          n -> sysDictService.getDictItems("SCM00015")
        );
      ReportReceivableVo finalVo = vo;
      currencyCodeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getCurrencyCode()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setCurrencyCode(i.getItemValue()),
          () ->
            ir.addError(
              "currencyCode",
              String.format(
                "必须为 %s 中之一",
                currencyCodeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setBeginningBalanceCurrencyAmount(
      SheetUtils.tryToDecimal(row.getBeginningBalanceCurrencyAmount())
    );
    vo.setIncomeAmount(SheetUtils.tryToDecimal(row.getIncomeAmount()));
    vo.setRefundAmount(SheetUtils.tryToDecimal(row.getRefundAmount()));
    vo.setSpendAmount(SheetUtils.tryToDecimal(row.getSpendAmount()));
    vo.setOther(SheetUtils.tryToDecimal(row.getOther()));
    vo.setConvertedSuccessAmount(
      SheetUtils.tryToDecimal(row.getConvertedSuccessAmount())
    );
    vo.setConvertedFailedAmount(
      SheetUtils.tryToDecimal(row.getConvertedFailedAmount())
    );
    vo.setEndingBalance(SheetUtils.tryToDecimal(row.getEndingBalance()));
    if (StringUtils.hasText(row.getReceivedState())) {
      vo.setReceivedState(
        ReportReceivableReceivedStateEnums.toValue(row.getReceivedState())
      );
      if (vo.getReceivedState() == null) {
        ir.addError("receivedState", "转账/到账金额只能是：“不相符”, “相符”");
      }
    }
    // 处理关联字段“店铺”
    if (
      !SheetUtils.isBlank(row.getSidsShopName()) &&
      SheetUtils.isBlank(row.getSids())
    ) {
      ShopInfoSearchParamPo sidsSearchParam = new ShopInfoSearchParamPo();
      sidsSearchParam.setLimit(2); // 最大只返回二行记录
      sidsSearchParam.setShopNameEq(SheetUtils.trim(row.getSidsShopName()));
      sidsSearchParam.applySqlSegments();
      List<ShopInfoItemVo> sidsMatches = shopInfoMapper.search(sidsSearchParam);
      if (sidsMatches.size() == 0) {
        ir.addError("sidsShopName", "未能在店铺中找到匹配的数据");
      } else if (sidsMatches.size() > 1) {
        ir.addError("sidsShopName", "关联不唯一，在店铺中找到多个匹配的数据");
      } else {
        vo.setSids(sidsMatches.get(0).getId());
      }
    }
    // 处理关联字段“站点”
    if (
      !SheetUtils.isBlank(row.getMidsCountry()) &&
      SheetUtils.isBlank(row.getMids())
    ) {
      SysCountrySearchParamPo midsSearchParam = new SysCountrySearchParamPo();
      midsSearchParam.setLimit(2); // 最大只返回二行记录
      midsSearchParam.setCountryEq(SheetUtils.trim(row.getMidsCountry()));
      midsSearchParam.applySqlSegments();
      List<SysCountryItemVo> midsMatches = sysCountryMapper.search(
        midsSearchParam
      );
      if (midsMatches.size() == 0) {
        ir.addError("midsCountry", "未能在国家中找到匹配的数据");
      } else if (midsMatches.size() > 1) {
        ir.addError("midsCountry", "关联不唯一，在国家中找到多个匹配的数据");
      } else {
        vo.setMids(midsMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<ReportReceivableImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<ReportReceivableImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            ReportReceivableImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              ReportReceivableImportPo row,
              AnalysisContext cxt
            ) {
              ReportReceivableVo vo = new ReportReceivableVo();
              ImportRow<ReportReceivableImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<ReportReceivableImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<ReportReceivableImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      ReportReceivableVo vo = new ReportReceivableVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    ReportReceivableSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "sids",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ReportReceivableItemVo) r).getSidsShopName())
          )
      );
      exportOptions.addFieldMappingOption(
        "mids",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ReportReceivableItemVo) r).getMidsCountry())
          )
      );
      exportOptions.addFieldMappingOption(
        "settleMonth",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "archiveStatus",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            ReportReceivableArchiveStatusEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "currencyCode",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00015")
      );
      exportOptions.addFieldMappingOption(
        "receivedState",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            ReportReceivableReceivedStateEnums.toLabel((String) o)
          )
      );
      exportOptions.addStringFields(
        "sidsShopName",
        "storeName",
        "midsCountry",
        "archiveStatus",
        "currencyCode",
        "remark",
        "receivedState",
        "currencyIcon"
      );

      String fileName = String.format(
        "应收报告(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> currencyCodeItems = sysDictService.getDictItems(
      "SCM00015"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<ReportReceivableExcelPo> items =
      new ArrayList<ReportReceivableExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<ReportReceivableItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<ReportReceivableItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (ReportReceivableItemVo item : list) {
        ReportReceivableExcelPo excel = new ReportReceivableExcelPo();
        BeanUtils.copyProperties(item, excel);
        excel.setArchiveStatus(
          ReportReceivableArchiveStatusEnums.toLabel(item.getArchiveStatus())
        );
        if (item.getCurrencyCode() != null) {
          currencyCodeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getCurrencyCode()))
            .findFirst()
            .ifPresent(i -> excel.setCurrencyCode(i.getItemText()));
        }
        excel.setReceivedState(
          ReportReceivableReceivedStateEnums.toLabel(item.getReceivedState())
        );

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "应收报告(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(ReportReceivableExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过店铺查询应收报告主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdBySids(Long sids) {
    return this.baseMapper.getIdBySids(sids);
  }

  /**
   * 通过店铺查询应收报告多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsBySids(List<Long> list) {
    return this.baseMapper.getIdsBySids(list);
  }

  /**
   * 通过应收报告主键查询店铺
   */
  @Override
  public Long getSidsById(Long id) {
    return this.baseMapper.getSidsById(id);
  }

  /**
   * 通过应收报告主键查询店铺列表
   */
  @Override
  public List<Long> getSidsByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getSidsByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (Long) stringObjectMap.get("sids"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 应收报告的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public ReportReceivableVo getVoById(Long id) throws Exception {
    ReportReceivableVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    ReportReceivableDetailSearchParamPo detailSearchParamPo =
      new ReportReceivableDetailSearchParamPo();
    detailSearchParamPo.setParentReportReceivable(id);
    // 禁用通用数据权限过滤
    detailSearchParamPo.setDisableDataPremissions(true);
    detailSearchParamPo.getExtendData().put("queryMode", "sub");
    detailSearchParamPo.getExtendData().put("queryParent", "ReportReceivable");
    detailSearchParamPo.applySqlSegments();
    vo.setDetail(reportReceivableDetailService.search(detailSearchParamPo));

    return vo;
  }

  /**
   * 分页查询应收报告
   * @param search 查询条件
   * @return 应收报告分页查询结果
   */
  @Override
  public Page<ReportReceivableItemVo> pageSearch(
    ReportReceivableSearchParamPo search
  ) {
    Page<ReportReceivableItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(ReportReceivableItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 应收报告快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'ReportReceivableOptions::' + #search.keyword"
  )
  public List<OptionItem<ReportReceivableItemVo>> searchOptions(
    ReportReceivableSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询应收报告
   * @param search 查询条件
   * @return 应收报告列表查询结果
   */
  @Override
  public List<ReportReceivableItemVo> search(
    ReportReceivableSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询应收报告最后更新时间
   * @param search 查询条件
   * @return 应收报告最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(ReportReceivableSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 交易报告对账
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了交易报告对账操作"
  )
  @Override
  public void reconciliation(Long id) throws Exception {
    if (reportReceivableReconciliationAction == null) {
      throw new Exception("此操作当前不可用");
    }
    reportReceivableReconciliationAction.run(id);
  }

  /**
   * 交易报告管理
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了交易报告管理操作"
  )
  @Override
  public void manage(Long id) throws Exception {
    if (reportReceivableManageAction == null) {
      throw new Exception("此操作当前不可用");
    }
    reportReceivableManageAction.run(id);
  }

  /**
   * 上传记录
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了上传记录操作"
  )
  @Override
  public void uploadRecord(Long id) throws Exception {
    if (reportReceivableUploadRecordAction == null) {
      throw new Exception("此操作当前不可用");
    }
    reportReceivableUploadRecordAction.run(id);
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    ReportReceivableSearchParamPo search = new ReportReceivableSearchParamPo();
    return MapUtil
      .builder()
      .put(
        "ReportReceivableViews",
        this.baseMapper.reportReceivableViewsCount(search)
      )
      .build();
  }

  /**
   * 应收报告视图
   */
  @Override
  public List<ReportReceivableItemVo> reportReceivableViews(
    ReportReceivableSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.reportReceivableViews(search);
  }

  /**
   * 应收报告视图分页
   */
  @Override
  public Page<ReportReceivableItemVo> reportReceivableViewsPage(
    ReportReceivableSearchParamPo search
  ) {
    Page<ReportReceivableItemVo> reportReceivableViewsPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return reportReceivableViewsPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return reportReceivableViewsPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    reportReceivableViewsPage =
      this.baseMapper.reportReceivableViewsPage(
          search.toPage(this.baseMapper.reportReceivableViewsCount(search)),
          search
        );
    List<Long> recordIds = reportReceivableViewsPage
      .getRecords()
      .stream()
      .map(ReportReceivableItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return reportReceivableViewsPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return reportReceivableViewsPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    reportReceivableViewsPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return reportReceivableViewsPage;
  }

  /**
   * 查询应收报告视图最后更新时间
   * @param search 查询条件
   * @return 应收报告视图最后更新时间
   */
  @Override
  public Date reportReceivableViewsLastUpdateTime(
    ReportReceivableSearchParamPo search
  ) {
    return this.baseMapper.reportReceivableViewsLastUpdateTime(search);
  }
}
